﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace Waaahsabi.Controls.DWM
{
#pragma warning disable 67
	// ReSharper disable UnaccessedField.Local
	[TemplateVisualState(Name = "Closed", GroupName = "Default")]
	[TemplateVisualState(Name = "Open", GroupName = "Default")]
	public class StartMenuProgramGroup : Control
	{
		private ToggleButton _tbtnHeader;
		private StackPanel _stkPrograms;
		private ItemsControl _itmPrograms;

		#region Items DependencyProperty
		public static readonly DependencyProperty ItemsProperty =
		DependencyProperty.Register
			(
			"Items",
			typeof(ObservableCollection<StartMenuProgramGroupItem>),
			typeof(StartMenuProgramGroup),
			new PropertyMetadata(null)
			);

		public ObservableCollection<StartMenuProgramGroupItem> Items
		{
			get { return (ObservableCollection<StartMenuProgramGroupItem>)GetValue(ItemsProperty); }
			set { SetValue(ItemsProperty, value); }
		}
		#endregion

		public static readonly DependencyProperty CategoryIdProperty =
		DependencyProperty.Register
			(
			"CategoryId",
			typeof(ulong),
			typeof(StartMenuProgramGroup),
			new PropertyMetadata(null)
			);

		public ulong CategoryId
		{
			get { return (ulong)GetValue(CategoryIdProperty); }
			set { SetValue(CategoryIdProperty, value); }
		}


		public static readonly DependencyProperty CategoryNameProperty =
		DependencyProperty.Register
			(
			"CategoryName",
			typeof(string),
			typeof(StartMenuProgramGroup),
			new PropertyMetadata("No Category Name")
			);

		public string CategoryName
		{
			get { return (string)GetValue(CategoryNameProperty); }
			set { SetValue(CategoryNameProperty, value); }
		}

		public event EventHandler GroupOpened;
		public event EventHandler GroupClosed;
		private bool _isOpen;

		public StartMenuProgramGroup()
		{
			DefaultStyleKey = typeof(StartMenuProgramGroup);
			Items = new ObservableCollection<StartMenuProgramGroupItem>();
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			
			_stkPrograms = GetTemplateChild("stkPrograms") as StackPanel;
			_itmPrograms = GetTemplateChild("itmPrograms") as ItemsControl;

			_tbtnHeader = GetTemplateChild("tbtnHeader") as ToggleButton;
			if (_tbtnHeader != null)
			{
				_tbtnHeader.Click += (s, e) =>
				{
					if (_isOpen)
					{
						Close();
					}
					else
					{
						if (GroupOpened != null)
							GroupOpened(this, null);
					}
				};
			}
			//Close();
		}

		public void Close()
		{
			VisualStateManager.GoToState(this, "Closed", true);
			_tbtnHeader.IsChecked = false;
			_isOpen = false;
		}

		public void Open()
		{
			VisualStateManager.GoToState(this, "Open", true);
			_isOpen = true;
		}
	}
	// ReSharper restore UnaccessedField.Local
#pragma warning restore 67
}
